/*
 * Copyright (c) 2017. Lorem ipsum dolor sit amet, consectetur adipiscing elit.
 * Morbi non lorem porttitor neque feugiat blandit. Ut vitae ipsum eget quam lacinia accumsan.
 * Etiam sed turpis ac ipsum condimentum fringilla. Maecenas magna.
 * Proin dapibus sapien vel ante. Aliquam erat volutpat. Pellentesque sagittis ligula eget metus.
 * Vestibulum commodo. Ut rhoncus gravida arcu.
 */

package com.mrd.gtimp.business.service.cargoDeclaration.component;

import com.mrd.gtimp.business.entity.CargoDeclaRecord;
import com.mrd.gtimp.business.entity.Declaration;
import com.mrd.gtimp.business.service.cargoDeclaration.mapper.ExportDelcarationMapper;
import com.mrd.gtimp.business.service.cargoDeclaration.mapper.ImportDelcarationMapper;
import com.mrd.gtimp.business.repository.CargoDeclaRecordDao;
import com.mrd.gtimp.business.repository.DeclarationDao;
import com.mrd.gtimp.fix.ChnToCodeFix;
import com.mrd.gtimpframe.entity.ComDeclaProp;
import com.mrd.gtimpframe.entity.ComDeclaWay;
import com.mrd.gtimpframe.repository.ComDeclaWayMapper;
import com.mrd.util.LoginUtil;
import com.mrd.util.PropertiesUtil;
import com.mrd.util.StringUtils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Properties;

import javax.annotation.Resource;

import bean.result.DeclaResult;
import helper.impl.CargoDeclarationImpl;
import helper.impl.ExportCargoDeclarationImpl;
import helper.impl.ImportCargoDeclarationImpl;
import mapper.Mapper;

/**
 * Created by dengdc on 2017/5/25.
 */
@Component
public class CargoDeclarationHelper {
    private static final Properties PROPERTIES = new Properties();
    private Logger logger = LoggerFactory.getLogger(CargoDeclarationHelper.class);

    @Resource
    private DeclarationDao declarationDao;
    @Resource
    private CargoDeclaRecordDao cargoDeclaRecordDao;
    @Resource
    private ChnToCodeFix chnToCodeFix;
    @Resource
    private ComDeclaWayMapper comDeclaWayMapper;

    public DeclaResult didUpload(String declarationId) throws Exception {
        //查报关单
        Declaration declaration = declarationDao.findOne(declarationId);
        if (!valid(declaration)) {
            return null;
        }
        //查公司的申报方式的
        ComDeclaWay query = new ComDeclaWay();
        String currLoginComId = LoginUtil.getLoginUser().getCompany().getId();
        query.setWayCode(ComDeclaWay.WayCodeEnum.GZ_PORT_HTTPS.toString());
        query.setStatus("1");
        query.setComId(currLoginComId);
        List<ComDeclaWay> results = comDeclaWayMapper.selective(query);
        if(CollectionUtils.isEmpty(results)){
            throw new RuntimeException("未开通广州版单一窗口");
        }
        ComDeclaWay upWay = results.get(0);
        Map<String, String> propMap = upWay.getPropMap();

        String userName = propMap.get(ComDeclaProp.PropKey.HTTP_COM_ACCOUNT.toString());
        String password = propMap.get(ComDeclaProp.PropKey.HTTP_COM_PWD.toString());
        String companyId = propMap.get(ComDeclaProp.PropKey.HTTP_COM_ID.toString());
        String companyCode = propMap.get(ComDeclaProp.PropKey.HTTP_COM_CODE.toString());

        String url = PropertiesUtil.getConfigProperties("import.url");
        //进出口状态
        String declarationType = declaration.getDeclaration_type();
        //查询报关状态
        CargoDeclaRecord record = cargoDeclaRecordDao.findByDidAndUploadWay(declarationId, ComDeclaWay.WayCodeEnum.GZ_PORT_HTTPS.toString());
        String invNo = "";
        String invPwd = "";
        if (record != null) {
            //获取关检号、关键密码
            invNo = record.getInvNo();
            invPwd = record.getInvPwd();
            invNo = StringUtils.isEmpty(invNo) ? "" : invNo;
            invPwd = StringUtils.isEmpty(invPwd) ? "" : invPwd;
            //更新时间
            record.setUpdateTime(new Date());
        } else {

            //新建报关记录
            record = new CargoDeclaRecord();
            record.setCteateTime(new Date());
            record.setUpdateTime(record.getCteateTime());
            record.setStatus("0");
            record.setUploadWay(ComDeclaWay.WayCodeEnum.GZ_PORT_HTTPS.toString());
            record.setDid(declarationId);
            record.setBusinessNo(declaration.getBusinessId());
            record.setCompanyId(companyId);
            record.setIeFlag(Declaration.DECLARATION_TYPE_EXPORT.equals(declarationType) ? "1" : "0");
            record.setTrnFlag("直航".equals(declaration.getData_type()) ? "0" : "1");
        }
        cargoDeclaRecordDao.save(record);

        Mapper mapper = null;
        CargoDeclarationImpl cargoDeclaration = null;
        //判断进出口，赋予不同的Mapper和工具类
        if (Declaration.DECLARATION_TYPE_EXPORT.equals(declarationType)) { //出口
            mapper = new ExportDelcarationMapper();
            cargoDeclaration = new ExportCargoDeclarationImpl();
        } else {
            mapper = new ImportDelcarationMapper();
            cargoDeclaration = new ImportCargoDeclarationImpl();
        }

        chnToCodeFix.chnToCode(declaration);
        chnToCodeFix.freightFix(declaration);

        //调用上传
        cargoDeclaration.set4LengthSerialNum(declaration.getBusinessId().substring(0, 4));
        cargoDeclaration.setBizEntity(declaration);
        cargoDeclaration.setMapper(mapper);
        cargoDeclaration.setInvNoAndPwd(invNo, invPwd);
        cargoDeclaration.setCompanyParameters(userName, password, companyId, companyCode);
        cargoDeclaration.setUrl(url);
        DeclaResult result = cargoDeclaration.send();//发送并返回结果
        logger.info(cargoDeclaration.toString());
        if (result.isSuccess()) {
            record.setStatus("4");//状态改为暂存
            record.setUpdateTime(new Date());
            record.setInvNo(result.getInvNo());
            record.setInvPwd(result.getInvPwd());
        } else {
            record.setStatus("-1");//状态改为上传失败
            record.setUpdateTime(new Date());
            result.setSuccess(false);
        }

        cargoDeclaRecordDao.save(record);
        if(!result.isSuccess()){
            throw new RuntimeException(result.getMessage());
        }
        return result;
    }

    /**
     * 校验报关单的报关行是否在白名单内
     */
    private boolean valid(Declaration dn) {
        String companyId = dn.getSupCompany().getId();
        String whiteList = PropertiesUtil.getConfigProperties("whiteList");
        String[] whiteListArr = whiteList.split(",");
        for (String cid : whiteListArr) {
            if (cid.equals(companyId)) {
                return true;
            }
        }
        return false;
    }
}
